package com.kelvem.saas.workbanch.fsm.resolver;

import com.kelvem.saas.workbanch.fsm.container.DaoContainer;
import com.kelvem.saas.workbanch.fsm.entity.Entity;
import org.springframework.aop.framework.AopProxyUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class MapperResolver {

    public static void resolve(Object bean, String beanName) {
        Class<?> beanProxyClass = AopProxyUtils.ultimateTargetClass(bean);
        Type[] daoInterfaces = beanProxyClass.getGenericInterfaces();
        for (Type daoType : daoInterfaces) {
            Type[] entityInterfaces = ((Class) daoType).getGenericInterfaces();
            for (Type entityType : entityInterfaces) {
                if (!(entityType instanceof ParameterizedType)) {
                    continue;
                }
                Type[] actualTypes = ((ParameterizedType) entityType).getActualTypeArguments();
                for (Type actualType:
                        actualTypes) {
                    if (!actualType.getTypeName().endsWith("Entity")) {
                        continue;
                    }
                    // todo
                    DaoContainer.addDao((Class<Entity>) actualType, beanName);
                }
            }
        }
    }
}
